import React from 'react';
import ajax from "decorate/ajax";
import Newest from 'business/newest';
import Pulldown from 'components/Pulldown';

class NewsItem extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        const { data = {}, important = 0, time = '', bold } = this.props;
        const { content = '' } = data;
        const date = new Date(time);
        return (
            <div className={`${Number(important) === 1 ? 'important' : ''} app-news-item-wrapper bottom-line`}>
                <div className="app-news-item-time">
                    {XUE.formatDate(date, 'hh:mm:ss')}
                </div>
                <div style={{fontWeight: bold ? '800' : 500 }} className="app-news-item-content" dangerouslySetInnerHTML={{__html: content}} />
            </div>
        );
    }
}

@ajax(Newest.url, Newest.meta, Newest.resolve)
export default class News extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
        };
    }

    componentWillReceiveProps(nextProps, nextContext) {
        const { data } = nextProps;
        if (this.props.data !== data) {
            this.setState({
                data,
            });
        }
    }

    componentDidMount() {
        XUE.Ws.subscribe(
          [{
              title: 'JIN10_NEWS_PUSH',
              callback: (response) => {
                  console.log(response);
                  if (response.id !== 'Newest') {
                      return;
                  }
                  const res = JSON.parse(response.data);
                  console.log(1111);
                  const { data = [] } = this.state;
                  const length = res.length;
                  for (let i = 0; i < length; i++) {
                      data.unshift(res.pop());
                  }
                  this.setState({
                      data,
                  });
              }
          }], 'Newest');
    }

    onPulldown = () => {
        return this.postAjax();
    }

    componentWillUnmount() {
       // XUE.unsubscribe('JIN10_NEWS_PUSH', 'Newest');
    }

    render() {
        const { data = [] } = this.state;
        if (data.length === 0) {
            return (
                <div className="app-news-wrapper">
                    <div className="no-data">暂无数据</div>
                </div>
            )
        }
        return (
          <Pulldown
            onLoading={this.onPulldown}
          >
              <div className="app-news-wrapper">
                  {
                      data.map((item) => {
                          return (
                            <NewsItem {...item} />
                          );
                      })
                  }
              </div>
          </Pulldown>

        );
    }
}
